import { useState } from 'react';
import { message } from 'antd';
import { experimentApi } from '../services/api';
import { ChartViewMode } from '../components/charts/types';

interface SeriesDataState {
  loading: boolean;
  data: any[];
  columns: Array<{ name: string; type: string }>;
  totalRows: number;
  currentPage: number;
  pageSize: number;
  hasMore: boolean;
}

/**
 * 管理序列数据加载和视图模式的自定义 Hook
 */
export const useSeriesData = (projectId: string | undefined, selectedExperimentId: number | null) => {
  // 序列数据的状态管理（key: seriesId）
  const [seriesDataMap, setSeriesDataMap] = useState<Record<number, SeriesDataState>>({});

  // 序列数据的显示模式和图表类型（key: seriesId）
  const [seriesViewMode, setSeriesViewMode] = useState<Record<number, ChartViewMode>>({});

  // 清空序列数据
  const clearSeriesData = () => {
    setSeriesDataMap({});
  };

  // 加载序列数据
  const loadSeriesData = async (seriesId: number, page: number = 1, pageSize: number = 100) => {
    if (!projectId || !selectedExperimentId) return;

    try {
      setSeriesDataMap(prev => ({
        ...prev,
        [seriesId]: { ...prev[seriesId], loading: true }
      }));

      const skip = (page - 1) * pageSize;
      const result = await experimentApi.getSeriesData(
        projectId,
        selectedExperimentId,
        seriesId,
        skip,
        pageSize
      );

      setSeriesDataMap(prev => ({
        ...prev,
        [seriesId]: {
          loading: false,
          data: result.data,
          columns: result.columns,
          totalRows: result.total_rows,
          currentPage: page,
          pageSize: pageSize,
          hasMore: result.has_more
        }
      }));
    } catch (error: any) {
      console.error('Failed to load series data:', error);
      message.error('加载序列数据失败');
      setSeriesDataMap(prev => ({
        ...prev,
        [seriesId]: { ...prev[seriesId], loading: false }
      }));
    }
  };

  // 获取或初始化序列的视图模式
  const getSeriesViewMode = (seriesId: number): ChartViewMode => {
    if (!seriesViewMode[seriesId]) {
      return { mode: 'table', chartType: 'column' };
    }
    return seriesViewMode[seriesId];
  };

  // 更新序列的视图模式
  const updateSeriesViewMode = (seriesId: number, updates: Partial<ChartViewMode>) => {
    setSeriesViewMode(prev => ({
      ...prev,
      [seriesId]: {
        ...getSeriesViewMode(seriesId),
        ...updates
      }
    }));
  };

  return {
    seriesDataMap,
    clearSeriesData,
    loadSeriesData,
    getSeriesViewMode,
    updateSeriesViewMode,
  };
};

